package com.za.plugin.transfer.func;



import com.za.plugin.pojo.Content;
import com.za.plugin.util.StrUtil;

import java.util.List;

// 把 date() 转为 to_date()  ，  存在 (date(now()) 这种情况, 下面代码无法使用分组的方式简化
public class DateFunctionTransfer implements FunctionTransfer {
    @Override
    public boolean isSupport(String sql) {
        return clearSpace(sql).contains(" date(");
    }

    private String clearSpace(String sql) {
        return sql.toLowerCase().replaceAll("([(,]+)\\s*date\\s*\\(", "$1 date(")
//                .replaceAll("[]+\\s*date\\s*\\(", "\\, date(")
                .replaceAll(" date\\s*\\("," date(");
    }

    @Override
    public String transfer(String sql) {
        sql = clearSpace(sql);
        if (sql.contains(" date(")) {
            int idx = sql.indexOf(" date("), left = 0;
            StringBuilder sb = new StringBuilder();
            while (idx >= 0) {
                Content expectContent = StrUtil.getExpectContent(sql, idx + 5);
                assert expectContent != null;
                int end = expectContent.getEnd();
                List<String> segment = StrUtil.getSegment(sql, idx + 6, end - 1);
                sb.append(sql, left, idx).append(" to_date(").append(segment.get(0)).append(")");
                idx = sql.indexOf(" date(", idx + 5);
                if (idx == -1) {
                    sb.append(sql.substring(end));
                }
                left = end;
            }
            sql = sb.toString();
        }
        return sql;
    }
}
